package org.windblog.core;

import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import org.windblog.core.entity.Link;
import org.windblog.core.filter.PersistenceFilter;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

public class LinkService {

	private static PersistenceManager pm = null;

	public static void setLink(Link link)
	{
		pm = PersistenceFilter.getManager();
		pm.makePersistent(link);
	}
	
	@SuppressWarnings("unchecked")
	public static List<Link> getLinks()
	{
		List<Link> links = new LinkedList<Link>();
		pm = PersistenceFilter.getManager();
		Query query = pm.newQuery(Link.class);;
		try {
			links = (List<Link>) query.execute();
			query.closeAll();
			return links;
		} catch (Exception ex) {
			return null;
		}
	}
	
	public static Link getLink(Key key) {
		if (key == null)
			return null;
		pm = PersistenceFilter.getManager();
		try {
			Link link = pm.getObjectById(Link.class, key);
			return link;
		} catch (Exception ex) {
			return null;
		}
	}
	
	public static Link getLink(String linkKey)
	{
		Key key = KeyFactory.stringToKey(linkKey);
		return getLink(key);
	}
	
	public static Link getLinkByName(String name)
	{
		if (name == null)
			return null;
		pm = PersistenceFilter.getManager();
		Query query = pm.newQuery(Link.class);
		query.setFilter("name == NameParam");
		query.declareParameters("String NameParam"); 
		try {
			@SuppressWarnings("unchecked")
			List<Link> results = (List<Link>) query.execute(name); 
			if(results.size()==0)
				return null;
			else 
				return results.get(0);
		} catch (Exception ex) {
			return null;
		}
	}
	
	public static void deleteLink(Link link)
	{
		pm = PersistenceFilter.getManager();
		pm.deletePersistent(link);
	}
	
	public static boolean isExist(String name)
	{
		Link link = getLinkByName(name);
		if(link!=null)
			return true;
		else
			return false;
	}

	public static void initService() {
		// TODO Auto-generated method stub
		Link link = new Link();
		link.setName("Windblog ");
		link.setUrl("http://code.google.com/p/windblog/");
		link.setDescription("Windblog");
		link.setTarget("_blank");
		link.setDate(new Date());
		link.setVisible(true);

		LinkService.setLink(link);
		
		Link link2 = new Link();
		link2.setName("Author's Blog ");
		link2.setUrl("http://ougesite.appspot.com/");
		link2.setDescription("Author's Blog");
		link2.setTarget("_blank");
		link2.setDate(new Date());
		link2.setVisible(true);

		LinkService.setLink(link2);
		
	}
}
